/*
 * Copyright 2011 Christoph Ludwig (christoph[at]chludwig.de). All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package de.chludwig.ehumanities.provenance.utils;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Auxiliary class that provides convenience methods for dealing with
 * {@link InputStream InputStreams} and {@link OutputStream OutputStreams}.
 */
public class StreamUtil {

  /**
   * The number of bytes in one Mebibyte.
   * 
   * @see http://en.wikipedia.org/wiki/Mebibyte
   */
  private static final int MEBI = 1024 * 1024;

  /**
   * The buffer used to copy data from one stream to another one.
   */
  private final byte[] buffer = new byte[MEBI];
  
  /**
   * Copies all available bytes from <code>source</code> to <code>dest</code>.
   * 
   * @param source
   *          The stream all data is read from.
   * @param dest
   *          The stream all data is written to.
   * @throws IOException
   *           A read or write operation failed.
   */
  public void transfer(InputStream source, OutputStream dest) throws IOException {
    for (int count = source.read(buffer); 0 <= count; count = source.read(buffer)) {
      dest.write(buffer, 0, count);
    }
  }

}
